package com.tools;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Random;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Vibrator;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.Toast;

public class SysInterfacePhone {
	private static SysInterfacePhone tools;

	public void setViewBackground(Context context, View view, String resname) {
		InputStream is;
		try {
			is = getInputStreamFromAssets(context, resname);
			Drawable drawable = BitmapDrawable.createFromStream(is, "src");
			view.setBackgroundDrawable(drawable);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static SysInterfacePhone invoker() {
		if (tools == null) {
			tools = new SysInterfacePhone();
		}
		return tools;
	}

	public String getApkPath(Context context) {
		return context.getFilesDir().getPath();
	}

	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time：2011-11-10 上午10:48:31
	 * @param is
	 * @return context
	 * @TODO 从数据流中读取文字
	 ***********************************************************/
	public String convertStreamToString(InputStream is) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is),
				8192);
		StringBuilder context = new StringBuilder();
		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				context.append(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
				return null;
			}
		}

		return context.toString();
	}

	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time：2011-11-22 下午02:35:50
	 * @param in
	 * @return
	 * @TODO 从数据流中读取字节
	 ***********************************************************/
	public byte[] readByteFormInputStream(InputStream in) {
		byte[] body = null;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		byte[] buffer = new byte[4096];
		int byteCount;
		try {
			while ((byteCount = in.read(buffer)) != -1) {
				out.write(buffer, 0, byteCount);
			}
		} catch (IOException e1) {
			MyLog.e("Error readInputStream" + e1.getMessage());
			e1.printStackTrace();
		}
		body = out.toByteArray();
		try {
			out.close();
		} catch (IOException e) {
			MyLog.e("Error closing input stream: " + e.getMessage());
		}
		return body;
	}

	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time：2011-11-10 上午10:50:29
	 * @return
	 * @TODO 是否有内存卡
	 ***********************************************************/
	public boolean isSD() {
		return android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED);
	}

	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time 2011-8-22 11:41:04
	 * @return 产品生产商
	 * @TODO 读取产品生产商The end-user-visible name for the end product
	 ***********************************************************/
	public String getSystemVersion() {
		return Build.MODEL;
	}

	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time：2011-10-21 上午11:30:38
	 * @param context
	 * @return 系统版本号
	 * @TODO The user-visible version string. E.g., "1.0" or "3.4b5".
	 ***********************************************************/
	public String getCurrentSdkVersion(Context context) {
		try {
			String s = Build.VERSION.RELEASE;
			return s;
		} catch (Exception e) {
			e.printStackTrace();
			return "unknow";
		}

	}

	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time：2011-8-15 下午03:05:49
	 * @param context
	 *            上下文
	 * @param tel
	 *            电话号码
	 * @param content
	 *            SMS内容
	 * @TODO 发送SMS
	 ***********************************************************/
	public void sendSMS(Context context, String tel, String content) {
		Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:"
				+ tel));
		intent.putExtra("sms_body", content);
		context.startActivity(intent);
	}

	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time：2011-8-15 下午03:05:10
	 * @TODO 拨打电话
	 ***********************************************************/
	public void callPhone(Context context, String tel) {
		Intent i = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + tel));
		context.startActivity(i);
	}

	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time：2011-8-15 下午03:18:43
	 * @param context
	 * @param addressArr
	 * @param subject
	 * @param content
	 * @TODO 发送EMAIL
	 ***********************************************************/
	public void sendMail(Context context, String[] addressArr, String subject,
			String content) {
		Intent i = new Intent();
		i.setAction(Intent.ACTION_SEND);
		i.setType("plain/text");
		i.putExtra(Intent.EXTRA_EMAIL, addressArr);
		if (subject != null && !subject.equals("")) {
			i.putExtra(Intent.EXTRA_SUBJECT, subject);
		}
		if (content != null && !content.equals("")) {
			i.putExtra(Intent.EXTRA_TEXT, content);
		}
		try {
			context.startActivity(i);
		} catch (Exception ex) {
			MyLog.e(ex);
		}
	}

	public int getScreenWidth(Context context) {
		if (TEMP_DATA.screenW < 0) {
			TEMP_DATA.screenW = context.getResources().getDisplayMetrics().widthPixels;
		}
		return TEMP_DATA.screenW;
	}

	public int getScreenHeight(Context context) {
		if (TEMP_DATA.screenH < 0) {
			TEMP_DATA.screenH = context.getResources().getDisplayMetrics().heightPixels;
		}
		return TEMP_DATA.screenH;
	}

	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time：2011-8-15 下午03:25:00
	 * @param context
	 * @param milliseconds
	 *            震动时间，单位豪秒
	 * @TODO 震动手机。
	 ***********************************************************/
	public void vibrateDevice(Context context, long milliseconds) {
		Vibrator vibrator = (Vibrator) context
				.getSystemService(Context.VIBRATOR_SERVICE);
		vibrator.vibrate(milliseconds);
	}

	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time：2011-8-15 下午03:07:05
	 * @param context
	 * @return
	 * @TODO 读取本机号码
	 ***********************************************************/
	public String getLine1Number(Context context) {
		TelephonyManager tm = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		return tm.getLine1Number();
	}

	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time：2011-8-15 下午03:07:49
	 * @param context
	 * @param cls
	 * @TODO ACTIVITY 跳转
	 ***********************************************************/
	public void changeActivity(Context context, Class<?> cls) {
		Intent intent = new Intent();
		intent.setClass(context, cls);
		context.startActivity(intent);
	}

	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time：2011-8-15 下午03:08:03
	 * @param context
	 * @param url
	 * @TODO 打开浏览器
	 ***********************************************************/
	public void openBrowser(Context context, String url) {
		Intent viewIntent = new Intent("android.intent.action.VIEW", Uri
				.parse(url));
		context.startActivity(viewIntent);
	}

	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time：2011-8-22 上午11:42:56
	 * @param context
	 * @param name
	 * @param mode文件保存权限
	 * @param data
	 * @TODO 保存文件到APK包目录下 提示：Context.MODE_WORLD_READABLE 全局可读 +
	 *       Context.MODE_WORLD_WRITEABLE 全局可写
	 ***********************************************************/
	public void saveFileToAPK(Context context, String name, int mode,
			byte[] data) {
		if (context != null && data != null && data.length > 0) {
			FileOutputStream fos = null;
			try {
				fos = context.openFileOutput(name, mode);
				fos.write(data);
			} catch (Exception ex) {
				MyLog.e(ex);
			} finally {
				try {
					fos.close();
				} catch (Exception ex) {
					MyLog.e(ex);
				}
			}
		}
	}

	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time：2011-8-22 上午11:45:55
	 * @param context
	 * @param path
	 *            路径
	 * @param name
	 *            文件名
	 * @return
	 * @TODO 从SD卡读取文件
	 ***********************************************************/
	public byte[] loadFileFromSDCard(Context context, String path, String name) {
		FileInputStream fis = null;
		byte[] data = null;
		try {
			File file = new File(path, name);
			fis = new FileInputStream(file);
			data = new byte[fis.available()];
			fis.read(data);
		} catch (Exception ex) {
			MyLog.e(ex);
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (Exception ex) {
					MyLog.e(ex);
				}
			}
		}

		return data;
	}

	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time：2011-8-22 上午11:47:22
	 * @param context
	 * @param fileName
	 *            文件名(包含路径)
	 * @return
	 * @throws Exception
	 * @TODO 从ASSETS读取资源
	 ***********************************************************/
	public InputStream getInputStreamFromAssets(Context context, String fileName)
			throws Exception {
		InputStream is = null;
		if (context != null && fileName != null)
			is = context.getAssets().open(fileName);
		return is;
	}

	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time：2011-8-22 上午11:46:28
	 * @param context
	 * @param filePath
	 * @return
	 * @TODO 删除文件（SD卡与APK包目录）
	 ***********************************************************/
	public boolean deleteFile(Context context, String filePath) {
		boolean ret = false;

		if (context != null) {
			File fileToDel = new File(filePath);
			if (fileToDel.isFile()) {
				ret = fileToDel.delete();
			}
		}
		return ret;
	}

	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time：2011-11-10 上午10:42:56
	 * @param bitmapName
	 *            图片名
	 * @TODO 从内存中删除指定名图片
	 ***********************************************************/
	public void destroyBitmap(String bitmapName) {
		bitmap_list.remove(bitmapName);
	}

	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time：2011-11-10 上午10:38:23
	 * @param context
	 * @param bitmapName
	 * @return
	 * @TODO 从内存中取图片,如果内存中没有图片，则从ASS中取出
	 ***********************************************************/
	HashMap<String, Bitmap> bitmap_list = new HashMap<String, Bitmap>();

	public Bitmap getBitmap(Context context, String bitmapName) {
		Bitmap bitmap = bitmap_list.get(bitmapName);
		if (bitmap == null) {
			bitmap = getBitmapFormAss(context, bitmapName);
			bitmap_list.put(bitmapName, bitmap);
		}
		return bitmap;
	}

	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time：2011-11-10 上午10:38:10
	 * @param context
	 * @param fileName
	 * @return
	 * @TODO 从ASS中取图片
	 ***********************************************************/
	public Bitmap getBitmapFormAss(Context context, String fileName) {
		InputStream is = null;
		try {
			is = context.getAssets().open(fileName);
			if (is == null)
				throw new NullPointerException("file path is error");
			return BitmapFactory.decodeStream(is);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time：2011-8-22 上午11:44:43
	 * @param context
	 * @param path
	 * @param name
	 * @param data
	 * @TODO 保存文件到SD卡
	 ***********************************************************/
	public void saveFile(Context context, String path, String name, byte[] data) {
		if (context != null && data != null && data.length > 0) {
			FileOutputStream fos = null;
			File file = null;
			try {
				File iMochaPath = new File(path);
				if (!iMochaPath.isDirectory()) {
					iMochaPath.mkdirs();
				}

				file = new File(path, name);
				if (file.exists()) {
					file.delete();
				}
				file.createNewFile();

				fos = new FileOutputStream(file);
				fos.write(data);
			} catch (Exception ex) {
				MyLog.e(ex);
			} finally {
				if (fos != null) {
					try {
						fos.close();
					} catch (Exception ex) {
						MyLog.e(ex);
					}
				}
			}
		}
	}

	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time：2011-11-10 上午10:52:51
	 * @param path
	 * @param fileName
	 * @return
	 * @TODO 在path目录下查找file文件
	 ***********************************************************/
	public String searchFile(String path, String file) {
		if (path == null || file == null) {
			return null;
		}
		File tempFile = new File(path);
		if (tempFile.list() == null) {
			return "";
		}
		int file_num = tempFile.list().length;
		for (int i = 0; i < file_num; i++) {
			File child_file = new File(path, tempFile.list()[i]);
			if (child_file.isDirectory()) {
				String file_name = child_file.getName();
				System.out.println(file_name);
				String child_path = child_file.getPath();
				String string = searchFile(child_path, file);
				if (string != null) {
					return file_name + "/" + string;
				}
			} else if (child_file.isFile()) {
				if (child_file.getName().equals(file)) {
					return file;
				}
			}
		}

		return null;
	}

	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time：2011-10-21 上午11:33:38
	 * @param folderPath
	 * @TODO 删除文件夹及文件夹内的所有文件
	 ***********************************************************/
	public void delFolder(String folderPath) {
		try {
			delAllFile(folderPath); // 删除完里面所有内容
			String filePath = folderPath;
			filePath = filePath.toString();
			java.io.File myFilePath = new java.io.File(filePath);
			myFilePath.delete(); // 删除空文件夹

		} catch (Exception e) {
			MyLog.println("删除文件夹操作出错");
			e.printStackTrace();

		}
	}

	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time：2011-10-21 上午11:52:23
	 * @param path
	 *            文件夹路径 如 c:/fqf
	 * @TODO 删除文件夹里面的所有文件
	 ***********************************************************/
	public void delAllFile(String path) {
		File file = new File(path);
		if (!file.exists()) {
			return;
		}
		if (!file.isDirectory()) {
			return;
		}
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
				temp = new File(path + tempList[i]);
			} else {
				temp = new File(path + File.separator + tempList[i]);
			}
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory()) {
				delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
				delFolder(path + "/" + tempList[i]);// 再删除空文件夹
			}
		}
	}

	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time：2011-10-21 上午11:42:57
	 * @param context
	 * @return
	 * @TODO 1.由SIM卡的IMEI进行MD5校验 <br/>
	 *       2.取MD5低十四位进行CRC16加密 <br/>
	 *       3.转化为十六进制字符串 <br/>
	 ***********************************************************/
	public String getGUID(Context context) {
		if (TEMP_DATA.iUid == null) {
			String ret = null;
			String uid = getSimIMEI(context);
			int len = uid == null ? 0 : uid.length();
			String fix = "";
			for (int i = 0; i < 16 - len; i++) {
				fix += "0";
			}
			ret = uid == null ? fix : fix + uid;
			String bytes = toMD5(ret.getBytes());
			ret = bytes.substring(bytes.length() - 14, bytes.length());
			long crc = JavaCode.cal_crc(ret.getBytes(), 14);
			crc = (crc & 0xff);
			String endRet = Long.toHexString(crc);
			endRet = (endRet.length() > 1 ? endRet : "0" + endRet);
			TEMP_DATA.iUid = ret + endRet;
		}
		return TEMP_DATA.iUid;
	}

	/***********************************************************
	 * @author sun.huang <br/>
	 *         MSN:jxhuanghua@yahoo.com.cn
	 * @version time：2011-10-21 上午11:41:32
	 * @param bytes
	 * @return
	 * @TODO MD5校验
	 ***********************************************************/
	public String toMD5(byte[] bytes) {
		MessageDigest md;
		String deviceIDHash;
		try {
			md = MessageDigest.getInstance("MD5");
			deviceIDHash = convertToHex(md.digest(bytes));
		} catch (NoSuchAlgorithmException e) {
			return null;
		}
		return deviceIDHash;
	}

	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time：2011-10-21 上午11:41:07
	 * @param data
	 * @return
	 * @TODO 转化为十六进制
	 ***********************************************************/
	public String convertToHex(byte[] data) {
		StringBuffer buf = new StringBuffer();
		for (byte element : data) {
			int halfbyte = (element >>> 4) & 0x0F;
			int two_halfs = 0;
			do {
				if ((0 <= halfbyte) && (halfbyte <= 9)) {
					buf.append((char) ('0' + halfbyte));
				} else {
					buf.append((char) ('a' + (halfbyte - 10)));
				}
				halfbyte = element & 0x0F;
			} while (two_halfs++ < 1);
		}
		return buf.toString();
	}

	class TempData {
		int iScreenDpiType = -1;
		int screenW = -1;
		int screenH = -1;
		String iUid = null;
		String imei = null;

	}

	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time 2011-8-15 03:06:28
	 * @param context
	 * @return
	 * @TODO 取得手机SIM卡内的IMEI（SIM卡信号唯一标识）
	 ***********************************************************/
	public String getSimIMEI(Context context) {
		if (TEMP_DATA.imei == null) {
			TelephonyManager tm = (TelephonyManager) context
					.getSystemService(Context.TELEPHONY_SERVICE);
			TEMP_DATA.imei = tm.getDeviceId();
		}
		return TEMP_DATA.imei;
	}

	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time 2011-8-15 03:06:42
	 * @param context
	 * @return
	 * @TODO 取得SIM卡的IMSI号
	 ***********************************************************/
	public String getSimIMSI(Context context) {
		TelephonyManager tm = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		return tm.getSubscriberId();
	}

	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time：2011-11-10 上午10:56:58
	 * @param zipInputStream
	 * @param outputDirectory
	 * @param context
	 * @return 解压后的文件大小
	 * @throws Exception
	 *             解压异常
	 * @TODO 解压Zip包数据流
	 ***********************************************************/
	public long unzip(InputStream zipInputStream, String outputDirectory,
			Context context) throws Exception {
		ZipInputStream in = new ZipInputStream(zipInputStream);
		ZipEntry z;
		String name = "";
		int counter = 0;
		long folderSize = 0;
		// boolean b = false;;
		while ((z = in.getNextEntry()) != null) {
			name = z.getName();
			folderSize += z.getSize();
			if (z.isDirectory()) {
				// b = true;
				MyLog.d(name + "is a folder");
				name = name.substring(0, name.length() - 1);
				File folder = new File(outputDirectory + File.separator + name);
				folder.mkdirs();
				counter++;

			} else {
				// b = true;
				MyLog.d(name + "is a normal file");
				File file = new File(outputDirectory + File.separator + name);
				file.createNewFile();
				FileOutputStream out = new FileOutputStream(file);
				int ch;
				byte[] buffer = new byte[1024];
				while ((ch = in.read(buffer)) != -1) {
					out.write(buffer, 0, ch);
					out.flush();
				}
				out.close();
			}
		}

		in.close();
		return folderSize;

	}

	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time：2011-11-10 上午11:04:53
	 * @param rnd
	 * @param min
	 * @param max
	 * @return
	 * @TODO 取一个在min与max之间的随机整数
	 ***********************************************************/
	public int getRnd(Random rnd, int min, int max) {
		return (rnd.nextInt() >>> 1) % (max - min + 1) + min;
	}

	private TempData TEMP_DATA = new TempData();

	public Toast createToast(Context context, String content) {

		return Toast.makeText(context, content, Toast.LENGTH_SHORT);
	}
	public AlertDialog createDialog(Context context, String content) {
		AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
		dialogBuilder.setMessage(content);
		return dialogBuilder.create();
	}

}
